package yesjava.news.dao;

import yesjava.news.entity.News;
import yesjava.news.utils.MyDbUtil;
import yesjava.news.utils.Page;

import java.sql.Connection;
import java.util.Arrays;
import java.util.List;

public class NewsDaoImpl implements NewsDao {


    @Override
    public List<News> selectAllNews() {
        String sql = " select id,content,title,checked,readCount,`show` from news ";
        return MyDbUtil.executeQuery(News.class, sql);
    }

    //  2 , 20
    public Page<News> selectByPage(int pageNo, int pageSize) {
        int count = MyDbUtil.getCount(" select count(*) from news ");
        String sql = " select id,content,title,checked,readCount,`show` from news limit ?,? ";
        List<News> records = MyDbUtil.executeQuery(News.class, sql, (pageNo - 1) * pageSize, pageSize);
        Page<News> page = new Page<>(pageNo, pageSize, count, records);
        return page;
    }

    /*

pageNo
pageSize
count
totalPage = (count/pageSize) +  (count%pageSize==0?0 :1 )


* */


    @Override
    public void insertNews(List<News> newsList) {
        String sql = " insert into news(title,content,checked,readCount,`show`,creator_by) value(?,?,?,?,?,?) ";
        Connection connection = MyDbUtil.getConnection();
        for (News news : newsList) {
            MyDbUtil.executeUpdate(connection, sql, news.getTitle(), news.getContent(), news.getChecked(), news.getReadCount(),news.getShow(),news.getCreatorBy());
        }
        MyDbUtil.closeConnection();
    }

    @Override
    public void deleteById(Integer... id) {//
        String str = "";
        for (int i = 0; i < id.length; i++) {
            str = str + "?,"; // ?,?,?,
        }
        String sql = " delete from news where id in ( " +str.substring(0,str.length()-1)+           " )  ";
        MyDbUtil.executeUpdate(sql, id);
    }

    @Override
    public News selectById(Integer id) {
        String sql = " select id,content,title,checked,readCount,`show`,creator_by 'creatorBy' from news where id = ? ";
        List<News> newsList = MyDbUtil.executeQuery(News.class, sql, id);
        return newsList.size() > 0 ? newsList.get(0):null;
    }

    @Override
    public void updateById(News news) {
        String sql = " update news set content=?,title=?,checked=?,readCount=?,`show`=? where id = ? ";
        MyDbUtil.executeUpdate(sql,news.getContent(),news.getTitle(),news.getChecked(),news.getReadCount(),news.getShow(),news.getId());
    }
}


